import * as ECharts from "echarts"; // 全部引入Echarts
import elementResizeDetectorMaker from "element-resize-detector";

const HANDLER = "_vue_resize_handler";

// 定义自定义指令
const chartResizeDirective = {
  mounted(el, binding) {
    el[HANDLER] = binding.value
      ? binding.value
      : () => {
          let chart = ECharts.getInstanceByDom(el);
          if (!chart) {
            return;
          }
          chart.resize();
        };

    // 监听绑定的 div 大小变化，更新 echarts 大小
    elementResizeDetectorMaker().listenTo(el, el[HANDLER]);

    // 添加 mounted 钩子以确保元素已经渲染完成
    onMounted(() => {
      console.log("Element is now in the DOM");
    });
  },
  beforeUnmount(el) {
    // 移除监听器
    elementResizeDetectorMaker().removeListener(el, el[HANDLER]);
    delete el[HANDLER];

    // 添加 beforeUnmount 钩子以确保在组件卸载前清理
    onBeforeUnmount(() => {
      console.log("Element will be removed from the DOM");
    });
  },
};

export default chartResizeDirective;
